package system

import (
	"errors"
	"fresh-shop-gin/global"
	"fresh-shop-gin/model/system"
)

type UserService struct{}

// 注册用户
func (s *UserService) Register(user *system.User) error {
	if err := user.HashPassword(); err != nil {
		return err
	}
	return global.DB.Create(user).Error
}

// 登录用户
func (s *UserService) Login(user *system.User) (*system.User, error) {
	var userDB system.User
	if err := global.DB.Where("user_name = ?", user.UserName).First(&userDB).Error; err != nil {
		return nil, err
	}
	if !userDB.CheckPassword(user.Password) {
		return nil, errors.New("密码错误")
	}
	return &userDB, nil
}

// 获取用户列表
func (s *UserService) GetUserList() ([]system.User, error) {
	var users []system.User
	if err := global.DB.Find(&users).Error; err != nil {
		return nil, err
	}
	return users, nil
}
